package com.example.seh.add.idle;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.seh.MainActivity;
import com.example.seh.R;
import com.example.seh.add.errands.AddErrandsActivity;
import com.example.seh.constant.Constant;
import com.example.seh.databinding.ActivityAddIdleBinding;
import com.example.seh.databinding.DialogChoosePicTypeBinding;
import com.example.seh.util.BackUtil;
import com.example.seh.util.JudgeContent;
import com.example.seh.util.UserMsg;


import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddIdleActivity extends AppCompatActivity {

    private static final String TAG = "SelectPictureActivity";
    private ActivityAddIdleBinding selectPictureBinding;
    private String imgPath = "";
    private LinkedList<File> files = new LinkedList<>();

    @BindView(R.id.lgl_label)
    TypeLabelGridLayout lglLabel;
    @BindView(R.id.tv_reset)
    TextView tvReset;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private List<FilterBean> typeLabelLists;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        selectPictureBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_idle);
        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        ButterKnife.bind(this);
        initEvent();
        initData();
        setViewData();
    }

    private void initData() {
        //流式布局数据
        typeLabelLists = new ArrayList<>();
        List<FilterBean.TableMode> list = new ArrayList<>();
        list.add(new FilterBean.TableMode("其他"));
        list.add(new FilterBean.TableMode("手表"));
        list.add(new FilterBean.TableMode("手机"));
        list.add(new FilterBean.TableMode("显示器"));
        list.add(new FilterBean.TableMode("游戏本"));
        list.add(new FilterBean.TableMode("轻薄本"));
        list.add(new FilterBean.TableMode("平板电脑"));
        list.add(new FilterBean.TableMode("键盘鼠标"));
        typeLabelLists.add(new FilterBean("电子产品", new FilterBean.TableMode("不限"), list));

        List<FilterBean.TableMode> list1 = new ArrayList<>();
        list1.add(new FilterBean.TableMode("其他"));
        list1.add(new FilterBean.TableMode("身体护理"));
        list1.add(new FilterBean.TableMode("洗发护发"));
        list1.add(new FilterBean.TableMode("口腔护理"));
        list1.add(new FilterBean.TableMode("纸品湿巾"));
        list1.add(new FilterBean.TableMode("女性护理"));
        list1.add(new FilterBean.TableMode("衣物清洁"));
        typeLabelLists.add(new FilterBean("生活用品", new FilterBean.TableMode("不限"), list1));

        List<FilterBean.TableMode> list2 = new ArrayList<>();
        list2.add(new FilterBean.TableMode("其他"));
        list2.add(new FilterBean.TableMode("正装"));
        list2.add(new FilterBean.TableMode("上衣"));
        list2.add(new FilterBean.TableMode("裤装"));
        list2.add(new FilterBean.TableMode("外套"));
        list2.add(new FilterBean.TableMode("帽子"));
        list2.add(new FilterBean.TableMode("鞋子"));
        typeLabelLists.add(new FilterBean("服饰", new FilterBean.TableMode("不限"), list2));

        List<FilterBean.TableMode> list3 = new ArrayList<>();
        list3.add(new FilterBean.TableMode("其他"));
        list3.add(new FilterBean.TableMode("教材"));
        list3.add(new FilterBean.TableMode("教辅"));
        list3.add(new FilterBean.TableMode("课外书籍"));
        list3.add(new FilterBean.TableMode("学习用具"));
        typeLabelLists.add(new FilterBean("图书文具", new FilterBean.TableMode("不限"), list3));

        List<FilterBean.TableMode> list4 = new ArrayList<>();
        list4.add(new FilterBean.TableMode("不限"));
        typeLabelLists.add(new FilterBean("其他", new FilterBean.TableMode("不限"), list4));
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void setViewData() {
        lglLabel.setColumnCount(4);
        lglLabel.setLabelBg(R.drawable.flow_popup);
        lglLabel.setGridData(typeLabelLists);
    }

    @OnClick({R.id.tv_reset, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_confirm:
//                lglLabel.JudgeSelected();
                Log.e("rcw", "label=" + lglLabel.getLabelData());
                break;
            case R.id.tv_reset:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        lglLabel.resetData();
                    }
                });

                break;
        }
    }

    /**
     * Initial Event
     */
    private void initEvent() {
        /**
         * 点击上方返回键
         */
        selectPictureBinding.idleBack.setOnClickListener(v -> {
            BackUtil.JumpBack(AddIdleActivity.this);

        });

        /**点击发布按钮
         *
         */
        selectPictureBinding.btnPublish1.setOnClickListener(v -> {
            if (Judge()) {
                if (lglLabel.JudgeSelected()){
                    AlertDialog.Builder dialog = new AlertDialog.Builder(AddIdleActivity.this);
                    dialog.setTitle("提示")
                            .setMessage("确定要发布吗")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    String title = selectPictureBinding.goodsTitle.getText().toString();
                                    String content = selectPictureBinding.idleContent.getText().toString();
                                    String address = selectPictureBinding.goodsAddress.getText().toString();

                                    String contents = title + content + address;
                                    JudgeContent.setData(contents, new JudgeContent.DataCallback() {
                                        @Override
                                        public void onFailure() {
                                            Log.e("fail","发送失败");
                                        }

                                        @Override
                                        public void onResponse(String data) {
                                            try {
                                                JSONObject jsonObject = new JSONObject(data);
                                                JSONArray wordList = jsonObject.getJSONArray("word_list");

                                                if (wordList.length() == 0) {
                                                    sendData();
                                                    BackUtil.Back(AddIdleActivity.this);
                                                    finish();
                                                } else {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Toast.makeText(AddIdleActivity.this,"发布内容包含敏感词汇，请修改后发布",Toast.LENGTH_LONG).show();
                                                        }
                                                    });
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });


                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                    dialog.create().show();
                }

            }
        });

        /**
         * 设置地址字符限制(14个)
         */
        selectPictureBinding.goodsAddress.setFilters(new InputFilter[]{new MyLengthFilter(14, getApplicationContext())});

        /**
         * 点击分类
         */
        selectPictureBinding.downArrow.setOnClickListener(v -> {
            //TypeLabelActivity.show(AddIdleActivity.this);
            if (selectPictureBinding.addCategory.getVisibility() == View.INVISIBLE) {
                selectPictureBinding.addCategory.setVisibility(View.VISIBLE);
            } else {
                selectPictureBinding.addCategory.setVisibility(View.INVISIBLE);
            }

        });


        /**
         * 选择图片
         */
        selectPictureBinding.ivHelpImageFirst.setOnClickListener(v -> {
            choosePictureDialog(10);
        });
        selectPictureBinding.ivHelpImageFirstDelete.setOnClickListener(v -> {
            if (!files.isEmpty()) {
                if (files.get(0) != null) {
                    files.set(0, null);
                }
            }
            Log.e("files", files.toString());
            selectPictureBinding.ivHelpImageFirstDelete.setVisibility(View.GONE);
            selectPictureBinding.ivHelpImageFirst.setImageResource(R.mipmap.ic_upload_image);
        });
        selectPictureBinding.ivHelpImageSecond.setOnClickListener(v -> {
            choosePictureDialog(11);
        });
        selectPictureBinding.ivHelpImageSecondDelete.setOnClickListener(v -> {
            if (!files.isEmpty()) {
                if (files.get(1) != null) {
                    files.set(1, null);
                }
            }
            Log.e("files", files.toString());
            selectPictureBinding.ivHelpImageSecondDelete.setVisibility(View.GONE);
            selectPictureBinding.ivHelpImageSecond.setImageResource(R.mipmap.ic_upload_image);
        });
        selectPictureBinding.ivHelpImageThird.setOnClickListener(v -> {
            choosePictureDialog(12);
        });
        selectPictureBinding.ivHelpImageThirdDelete.setOnClickListener(v -> {
            if (!files.isEmpty()) {
                if (files.get(2) != null) {
                    files.set(2, null);
                }
            }
            Log.e("files", files.toString());
            selectPictureBinding.ivHelpImageThirdDelete.setVisibility(View.GONE);
            selectPictureBinding.ivHelpImageThird.setImageResource(R.mipmap.ic_upload_image);
        });
    }

    private boolean Judge() {
        String money = selectPictureBinding.goodsMoney2.getText().toString().trim();
        String title = selectPictureBinding.goodsTitle.getText().toString().trim();
        String content = selectPictureBinding.idleContent.getText().toString().trim();

        if (title.isEmpty()) {
            Toast.makeText(this, "请输入商品名称", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (content.isEmpty()) {
            Toast.makeText(this, "请输入转手原因", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (money.isEmpty()) {
            Toast.makeText(this, "请输入合适的价格", Toast.LENGTH_SHORT).show();
            return false;
        }


        return true;

    }

    /**
     * 发布数据
     */
    private void sendData() {
        String authorId = "3";
        String title = selectPictureBinding.goodsTitle.getText().toString();
        String content = selectPictureBinding.idleContent.getText().toString();
        String address = selectPictureBinding.goodsAddress.getText().toString();
        String price = selectPictureBinding.goodsMoney2.getText().toString();
        String category = lglLabel.getLabelData().toString();
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);


        requestBodyBuilder.addFormDataPart("addressName", address)
                .addFormDataPart("goodsName", title)
                .addFormDataPart("goodsPrice", price)
                .addFormDataPart("goodsDesc", content)
                .addFormDataPart("goodsCategory", category)
                .addFormDataPart("userId", String.valueOf(UserMsg.userDTO.getUserId()));



        for (File file : files) {
            if (file!=null&&file.getName() != null) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                requestBodyBuilder.addFormDataPart("files", file.getName(), requestBody);
            }
        }


        RequestBody requestBody2 = requestBodyBuilder.build();

        Request request = new Request.Builder()
                .url(Constant.ADD_IDLE)
                .header("Content-Type", "multipart/form-data")
                .post(requestBody2)
                .build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OkHttp", "发送失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("OkHttp", "发送成功");
            }
        });
    }


    /**
     * 判断用户输入字符长度
     */
    class MyLengthFilter implements InputFilter {

        private final int mMax;
        private Context context;

        public MyLengthFilter(int max, Context context) {
            mMax = max;
            this.context = context;
        }

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            int keep = mMax - (dest.length() - (dend - dstart));
            if (keep <= 0) {
                //这里，用来给用户提示
                Toast.makeText(context, "字数不能超过" + mMax, Toast.LENGTH_SHORT).show();
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
                keep += start;
                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        return "";
                    }
                }
                return source.subSequence(start, keep);
            }
        }

        /**
         * @return the maximum length enforced by this input filter
         */
        public int getMax() {
            return mMax;
        }
    }

    /**
     * 选择拍照/相册图片
     *
     * @param type 打开类型区分码
     */
    private void choosePictureDialog(int type) {
        View chooseTypeView = LayoutInflater.from(this).inflate(R.layout.dialog_choose_pic_type, null);
        AlertDialog selectDialog = new AlertDialog.Builder(this).setView(chooseTypeView).setCancelable(false).create();
        selectDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
        selectDialog.show();

        //设置弹窗在底部
        Window window = selectDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.main_menu_animStyle);

        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
        WindowManager.LayoutParams p = selectDialog.getWindow().getAttributes(); //获取对话框当前的参数值
        p.width = d.getWidth(); //宽度设置为屏幕
        selectDialog.getWindow().setAttributes(p); //设置生效


        Objects.requireNonNull(selectDialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        DialogChoosePicTypeBinding binding = DataBindingUtil.bind(chooseTypeView);
        binding.tvChoosePicCamera.setOnClickListener(v -> {
            selectDialog.dismiss();
            // 拉起相机
            openCamera(type);
        });
        binding.tvChoosePicGallery.setOnClickListener(v -> {
            selectDialog.dismiss();
            // 打开相册
            openGallery(type);
        });
        binding.tvChoosePicCancel.setOnClickListener(v -> selectDialog.dismiss());
    }

    /**
     * 打开相机
     *
     * @param type 打开类型区分码
     */
    private void openCamera(int type) {
        // 创建照片存储目录
        File imgDir = new File(getFilePath(null));
        // 创建照片
        String photoName = System.currentTimeMillis() + ".png";
        File picture = new File(imgDir, photoName);
        if (!picture.exists()) {
            try {
                picture.createNewFile();
            } catch (IOException e) {
                Log.e(TAG, "choosePictureTypeDialog: 创建图片失败", e);
            }
        }
        imgPath = picture.getAbsolutePath();
        // 调用相机拍照
        Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camera.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, "com.example.seh.fileprovider", picture));
        startActivityForResult(camera, type);
    }

    /**
     * 打开相册
     *
     * @param type 打开类型区分码
     */
    private void openGallery(int type) {
        Intent gallery = new Intent(Intent.ACTION_PICK);
        gallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(gallery, type);
    }

    public String getRealPathFromURI(Uri uri) {
        String filePath = null;
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                File cacheDir = getCacheDir();
                File tempFile = File.createTempFile("image", null, cacheDir);
                tempFile.deleteOnExit();
                String tempFilePath = tempFile.getAbsolutePath();
                FileUtils.copyInputStreamToFile(inputStream, tempFile);
                filePath = tempFilePath;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拉起相机回调data为null，打开相册回调不为null
        switch (requestCode) {
            case 0:
                Toast.makeText(this, "权限获得", Toast.LENGTH_SHORT).show();
                break;
            case 10:
                if (resultCode == RESULT_CANCELED) {
                    return;
                } else {
                    //真机是data,模拟机是data.getData()
                    if (data == null && !imgPath.isEmpty()) {
                        Glide.with(this).load(imgPath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(selectPictureBinding.ivHelpImageFirst);
                        Uri uri = Uri.fromFile(new File(imgPath));
                        if (!files.isEmpty()) {

                            files.set(0, new File(imgPath));

                        } else {
                            files.add(0, new File(imgPath));
                        }
                        System.out.println("10:" + uri);
                        selectPictureBinding.ivHelpImageFirstDelete.setVisibility(View.VISIBLE);
                        selectPictureBinding.ivHelpImageSecond.setVisibility(View.VISIBLE);
                    } else if (data.getData() != null) {
                        Glide.with(this).load(data.getData()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(selectPictureBinding.ivHelpImageFirst);
                        Uri selectedImage = data.getData();
                        String imagePath = getRealPathFromURI(selectedImage);
                        if (!files.isEmpty()) {
                            // 执行其他操作，例如添加到文件列表等
                            files.set(0, new File(imagePath));
                        } else {
                            if (imagePath != null) {
                                // 执行其他操作，例如添加到文件列表等
                                files.add(0, new File(imagePath));
                            }
                        }

                        selectPictureBinding.ivHelpImageFirstDelete.setVisibility(View.VISIBLE);
                        selectPictureBinding.ivHelpImageSecond.setVisibility(View.VISIBLE);
                    }
                }

                break;
            case 11:
                if (resultCode == RESULT_CANCELED) {
                    return;
                } else {
                    if (data == null && !imgPath.isEmpty()) {
                        Glide.with(this).load(imgPath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(selectPictureBinding.ivHelpImageSecond);
                        Uri uri = Uri.fromFile(new File(imgPath));
                        if (!files.isEmpty()) {
                            if (files.size() > 1) {
                                files.set(1, new File(imgPath));
                            } else {
                                files.add(1, new File(imgPath));
                            }
                        }
                        System.out.println("11:" + uri);
                        selectPictureBinding.ivHelpImageSecondDelete.setVisibility(View.VISIBLE);
                        selectPictureBinding.ivHelpImageThird.setVisibility(View.VISIBLE);
                    } else if (data.getData() != null) {
                        Glide.with(this).load(data.getData()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(selectPictureBinding.ivHelpImageSecond);
                        Uri selectedImage = data.getData();
                        String imagePath = getRealPathFromURI(selectedImage);
                        if (!files.isEmpty()) {
                            // 执行其他操作，例如添加到文件列表等
                            if (files.size() > 1) {
                                files.set(1, new File(imagePath));
                            } else {
                                if (imagePath != null) {
                                    // 执行其他操作，例如添加到文件列表等
                                    files.add(1, new File(imagePath));
                                }
                            }
                        }
                        selectPictureBinding.ivHelpImageSecondDelete.setVisibility(View.VISIBLE);
                        selectPictureBinding.ivHelpImageThird.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case 12:
                if (resultCode == RESULT_CANCELED) {
                    return;
                } else {
                    if (data == null && !imgPath.isEmpty()) {
                        Glide.with(this).load(imgPath).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(selectPictureBinding.ivHelpImageThird);
                        if (!files.isEmpty()) {
                            if (files.size() > 2) {
                                files.set(2, new File(imgPath));
                            } else {
                                files.add(2, new File(imgPath));
                            }
                        }
                        selectPictureBinding.ivHelpImageThirdDelete.setVisibility(View.VISIBLE);
                    } else if (data.getData() != null) {
                        Glide.with(this).load(data.getData()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(selectPictureBinding.ivHelpImageThird);
                        Uri selectedImage = data.getData();
                        String imagePath = getRealPathFromURI(selectedImage);
                        if (!files.isEmpty()) {
                            // 执行其他操作，例如添加到文件列表等
                            if (files.size() > 2) {
                                files.set(2, new File(imagePath));
                            } else {
                                if (imagePath != null) {
                                    // 执行其他操作，例如添加到文件列表等
                                    files.add(2, new File(imagePath));
                                }
                            }
                        }
                        selectPictureBinding.ivHelpImageThirdDelete.setVisibility(View.VISIBLE);
                    }
                }
                break;
            default:
                break;
        }
        imgPath = "";
    }

    /**
     * 获取存储文件路径
     *
     * @param dir 选择目录
     * @return 路径
     */
    public String getFilePath(String dir) {
        String path;
        // 判断是否有外部存储，是否可用
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            path = getExternalFilesDir(dir).getAbsolutePath();
        } else {
            // 使用内部储存
            path = getFilesDir() + File.separator + dir;
        }
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }

    /**
     * 如果用户点了返回键
     *
     * @param keyCode
     * @param event
     * @return
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BackUtil.JumpBack(AddIdleActivity.this);
        }
        return false;
    }
}